package connect3.team7.util;

import java.sql.*;
import java.util.*;
import java.io.*;
import oracle.jdbc.pool.OracleDataSource;

public class DBController {
  private static DBController instance;
  private Connection conn;

  private DBController() {
    super();
    connect();
  }

  public static DBController getInstance() {
    if (instance == null)
      instance = new DBController();

    return instance;
  }

  private void connect() {
    try {
      OracleDataSource ods = new OracleDataSource();
      Properties prop = ConfigProperties.getConfigProperties();
      ods.setURL(prop.getProperty("jdbc.url"));
      ods.setUser(prop.getProperty("jdbc.username"));
      ods.setPassword(prop.getProperty("jdbc.password"));

      conn = ods.getConnection();
    } catch(SQLException e) {
      e.printStackTrace();
    }
  }

  public void insertHost(HostConnectionSettings host) {
    try {
      PreparedStatement pstmt = conn.prepareStatement("insert into host_listing values (?,?,?,?,?)");  

      pstmt.setString(1,host.getHandle());
      pstmt.setString(2,host.getIP());
      pstmt.setInt(3,host.getPort());
      pstmt.setInt(4,host.getPlayerSlots());
      pstmt.setInt(5,host.getTimeLimit());

      pstmt.execute();
      
      pstmt.close();
    } catch (SQLException ex) {
      if (ex.getErrorCode() == 1)
        System.out.println("reusing prior host entry ...");
      else
        ex.printStackTrace();
    }
  }

  public ArrayList<HostConnectionSettings> getHostListing() {
    ArrayList<HostConnectionSettings> ret = new ArrayList();

    try {
      Statement stmt = conn.createStatement();
  
      ResultSet rs = stmt.executeQuery("select host_handle, host_ip, host_port, no_of_players, time_limit from host_listing");
  
      while (rs.next()) {
        HostConnectionSettings cs = new HostConnectionSettings(); 
  
        cs.setHandle(rs.getString(1));
        cs.setIP(rs.getString(2));
        cs.setPort(rs.getInt(3));
        cs.setPlayerSlots(rs.getInt(4));
        cs.setTimeLimit(rs.getInt(5));
  
        ret.add(cs);      

      }
      stmt.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
  
    return ret;
  } 
}
